package com.zgis.monitor.controller;

import com.zgis.monitor.config.MonitorConfig;
import com.zgis.monitor.model.ServiceStatus;
import com.zgis.monitor.model.dto.ServiceListDTO;
import com.zgis.monitor.service.MonitorService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

/**
 * 架空服务控制器
 */
@RestController
@RequestMapping("/api/monitor")
@RequiredArgsConstructor
public class MonitorController
{

    private final MonitorService monitorService;
    private final MonitorConfig  monitorConfig;

    /**
     * 获取所有服务状态
     */
    @GetMapping("/status")
    public ResponseEntity<List<ServiceStatus>> getAllStatus()
    {
        return ResponseEntity.ok(monitorService.getAllServiceStatus());
    }

    /**
     * 获取所有被监控服务的列表，包含基本信息和状态
     */
    @GetMapping("/servicelist")
    public List<ServiceListDTO> getServiceList()
    {
        // 调用服务层方法获取整合后的服务列表数据
        return monitorService.getServiceListWithStatus();
    }

    /**
     * 获取单个服务状态
     */
    @GetMapping("/status/{serverIp}/{serviceId}")
    public ResponseEntity<ServiceStatus> getStatus(
            @PathVariable String serverIp,
            @PathVariable String serviceId)
    {

        // 查找服务器配置
        Optional<MonitorConfig.ServerConfig> serverOpt = monitorConfig.getServers().stream()
                .filter(s -> s.getIp().equals(serverIp))
                .findFirst();


        // 查找服务配置
        Optional<MonitorConfig.ServiceConfig> serviceOpt = serverOpt.get().getServices().stream()
                .filter(s -> s.getId().equals(serviceId))
                .findFirst();

        // 检查状态
        ServiceStatus status = monitorService.checkStatus(serverOpt.get(), serviceOpt.get());
        return ResponseEntity.ok(status);
    }

    /**
     * 启动服务
     */
    @PostMapping("/start/{serverIp}/{serviceId}")
    public ResponseEntity<String> startService(
            @PathVariable String serverIp,
            @PathVariable String serviceId)
    {

        return operateService(serverIp, serviceId, true);
    }

    /**
     * 停止服务
     */
    @PostMapping("/stop/{serverIp}/{serviceId}")
    public ResponseEntity<String> stopService(
            @PathVariable String serverIp,
            @PathVariable String serviceId)
    {

        return operateService(serverIp, serviceId, false);
    }

    /**
     * 重启服务
     */
    @PostMapping("/restart/{serverIp}/{serviceId}")
    public ResponseEntity<String> restartService(
            @PathVariable String serverIp,
            @PathVariable String serviceId)
    {

        // 查找服务器和服务配置
        Optional<MonitorConfig.ServerConfig> serverOpt = monitorConfig.getServers().stream()
                .filter(s -> s.getIp().equals(serverIp))
                .findFirst();

        Optional<MonitorConfig.ServiceConfig> serviceOpt = serverOpt.get().getServices().stream()
                .filter(s -> s.getId().equals(serviceId))
                .findFirst();

        boolean success = monitorService.restartService(serverOpt.get(), serviceOpt.get());
        return success ?
                ResponseEntity.ok("服务重启成功") :
                ResponseEntity.internalServerError().body("服务重启失败");
    }

    /**
     * 通用操作服务方法
     */
    private ResponseEntity<String> operateService(String serverIp, String serviceId, boolean start)
    {
        // 查找服务器和服务配置
        Optional<MonitorConfig.ServerConfig> serverOpt = monitorConfig.getServers().stream()
                .filter(s -> s.getIp().equals(serverIp))
                .findFirst();

        Optional<MonitorConfig.ServiceConfig> serviceOpt = serverOpt.get().getServices().stream()
                .filter(s -> s.getId().equals(serviceId))
                .findFirst();

        boolean success;
        if (start)
        {
            success = monitorService.startService(serverOpt.get(), serviceOpt.get());
        }
        else
        {
            success = monitorService.stopService(serverOpt.get(), serviceOpt.get());
        }

        String action = start ? "启动" : "停止";
        return success ?
                ResponseEntity.ok("服务" + action + "成功") :
                ResponseEntity.internalServerError().body("服务" + action + "失败");
    }
}
    